package edu.wfu.preparedDishes.user.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Objects;

@Slf4j(topic = "c")
@Service
public class Code2SessionService {
    private static final String CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String APP_ID = "wxba66a66a12ded5c1";
    private static final String APP_SECRET = "e06fbe9696a4409c974cc64ca194ac4c";

    /**
     * 接受code发送到wx，获取openid，把openid存到user表
     *
     * @param code 前端传的code
     * @return ResultData
     */
    public  ResponseEntity<ResultData> getSessionInfo(String code) {
       try{
           String url = CODE2SESSION_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
           RestTemplate restTemplate = new RestTemplate();
           ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
           if (responseEntity.getStatusCode().is2xxSuccessful()) {
               String responseData = responseEntity.getBody();
               ObjectMapper objectMapper = new ObjectMapper();
               JsonNode jsonNode = objectMapper.readTree(responseData);
               ResultData resultData = objectMapper.convertValue(jsonNode, ResultData.class);
               String errcode = resultData.getErrcode();
               if (Objects.isNull(errcode)) {
                   return ResponseEntity.ok(resultData);
               } else {
                   throw new IllegalStateException("code2Session请求失败");
               }
           }
           return null;
       }catch (Exception e) {
           log.error("{}", e.getMessage());
           throw new IllegalStateException("code2Session请求失败");
       }
    }

    /**
     *
     */
    @Data
    @Accessors(chain = true)
    public static class ResultData {
        private String openid;
        private String session_key;
        private String unionid;
        private String errcode;
        private String errmsg;
    }
}
